package com.woniuxy.woniuticket.moviemodule.controller;




import com.github.pagehelper.PageInfo;
import com.woniuxy.woniuticket.moviemodule.pojo.ScheduleMsg;
import com.woniuxy.woniuticket.moviemodule.service.CinemaHallService;
import com.woniuxy.woniuticket.moviemodule.service.CinemaMoviesService;
import com.woniuxy.woniuticket.moviemodule.service.MovieinfoService;
import com.woniuxy.woniuticket.moviemodule.service.ScheduleService;
import com.woniuxy.woniuticket.moviemodule.utils.DateFormUtils;
import com.woniuxy.woniuticket.moviemodule.utils.FileEntity;
import com.woniuxy.woniuticket.moviemodule.utils.FileUploadTool;
import com.woniuxy.woniuticket.moviemodule.utils.UnloadFile;
import com.woniuxy.woniuticket.pojo.CinemaHall;
import com.woniuxy.woniuticket.pojo.CinemaMovies;
import com.woniuxy.woniuticket.pojo.CinemaSchedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalTime;
import java.util.*;

@Controller
@CrossOrigin
@RequestMapping("/schedule")
public class ScheduleController {
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private MovieinfoService movieinfoService;
    @Autowired
    private CinemaHallService cinemaHallService;
    @Value("${upload.location}")
    private String path;




    //排片>>先查询电影回显给前台,然后再添加排片表
    @RequestMapping("/queryMovie")
    public ModelAndView queryMovie(){
        ModelAndView mav =new ModelAndView();
        //查询放映室
        List<CinemaHall> halls=cinemaHallService.selectAllHall();
        mav.addObject("halls",halls);
        //查询已有电影
        Integer a=1;
        Integer b=10;
        List<CinemaMovies> list= movieinfoService.queryMovie(a,b);
        mav.addObject("list",list);
        mav.setViewName("/moviemanager/pages/webAdmin/addschedule.html");
        return mav;
    }

    /***
     *排片
     * @param begin电影开始时间
     * @param end电影结束时间
     * @param schedule订单对象
     * @return
     */
    @RequestMapping("/insertSchedule")
    public String insertSchedule( String begin, String end,
                                 CinemaSchedule schedule){
        Date begintime= DateFormUtils.dateform(begin);
        Date endtime= DateFormUtils.dateform(end);
        schedule.setBegintime(begintime);
        schedule.setEndtime(endtime);
        if (scheduleService.insertSchedule(schedule)>0){
            return "redirect:/moviemanager/index.html";
        }
        return "fail";
    }

    //上传电影
    @RequestMapping("/insertMovie")
    public String insertMovie(CinemaMovies movies, @RequestParam("imga")MultipartFile file,
                              @RequestParam("ved")MultipartFile file1, HttpServletRequest request) {

        String fileName1 = file1.getOriginalFilename();//获取真实的文件名称
        String newFileName1 = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date())+fileName1;
        String url1 = null;
        try {
            url1 = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File f1 = new File(url1+path);
        if(!f1.exists()){
            f1.mkdirs();//创建目录
        }
        try {
            FileCopyUtils.copy(file1.getBytes(),new File(f1.getAbsolutePath(),newFileName1));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String b="/"+path+newFileName1;
        b = b.substring(b.indexOf("static")+"static".length());
        movies.setVediosrc(b);
        String fileName = file.getOriginalFilename();//获取真实的文件名称
        String newFileName = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date())+fileName;
        String url = null;
        try {
            url = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File f = new File(url+path);
        if(!f.exists()){
            f.mkdirs();//创建目录
        }
        try {
            FileCopyUtils.copy(file.getBytes(),new File(f.getAbsolutePath(),newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String a="/"+path+newFileName;
        a = a.substring(a.indexOf("static")+"static".length());
           movies.setImg(a);

        if (movieinfoService.insertMovie(movies)>0){
            return "redirect:/moviemanager/index.html";
        }
        return "fail";
    }

    /**
     * 热点消息
     * 查出一天内有排片信息的电影
     * @return
     */
    @RequestMapping("/msg")
    public ModelAndView message(){
        List<CinemaMovies> list= movieinfoService.queryAllSchedule1();
        ModelAndView mav=new ModelAndView();
        mav.addObject("list",list);
        mav.setViewName("moviemanager/pages/webAdmin/schedule_msg");
        return mav;
    }

    /**
     * 通过排片id查询该场电影的具体信息
     * @return
     */
    @RequestMapping("/showschedule/{id}")
    public ModelAndView scheduleMsg(@PathVariable("id") Integer scheduleId){
        ScheduleMsg scheduleMsg= scheduleService.queryScheduleMsg(scheduleId);
        ModelAndView mav=new ModelAndView();
        mav.addObject("scheduleMsg",scheduleMsg);
        mav.setViewName("movieshow/msgmovie");
        return mav;
    }


    //查出所有电影进行管理
    @RequestMapping("/queryAllMovie")
    @ResponseBody
    public Map queryUserInfo1(@RequestParam(value = "page",defaultValue = "1",required = false) Integer page,@RequestParam(value = "limit",defaultValue = "5",required = false) Integer limit){
        List<CinemaMovies> list=movieinfoService.queryMovie(page,limit);
        PageInfo<CinemaMovies> info = new PageInfo<>(list);
        Map map=new HashMap();
        map.put("code",0);
        map.put("msg","");
        map.put("count",info.getTotal());
        map.put("data",list);
        return map;
    }

      //电影下架
    @RequestMapping("/delMovie")
    @ResponseBody
    public String delMovie(String arr){
        System.out.println(arr);
        String[] ids=arr.split(",");
        Integer[] moviesIds=new Integer[ids.length];
        for(int i=0;i<ids.length;i++){
            moviesIds[i]=Integer.parseInt(ids[i]);
        }
        movieinfoService.delMovie(moviesIds);
        return "success";
    }

    //查出所有排片     queryAllSchedule
    @RequestMapping("/queryAllSchedule")
    @ResponseBody
    public Map queryAllSchedule(@RequestParam(value = "page",defaultValue = "1",required = false) Integer page,@RequestParam(value = "limit",defaultValue = "5",required = false) Integer limit){
        List<ScheduleMsg> list=scheduleService.queryAllSchedule(page,limit);
        PageInfo<ScheduleMsg> info = new PageInfo<>(list);
        Map map=new HashMap();
        map.put("code",0);
        map.put("msg","");
        map.put("count",info.getTotal());
        map.put("data",list);
        return map;
    }

    //排片下架
    @RequestMapping("/delSchedule")
    @ResponseBody
    public String delSchedule(String arr){
        System.out.println(arr);
        String[] ids=arr.split(",");
        Integer[] scheduleids=new Integer[ids.length];
        for(int i=0;i<ids.length;i++){
            scheduleids[i]=Integer.parseInt(ids[i]);
        }
        scheduleService.delSchedule(scheduleids);
        return "success";
    }

    /**
     * 通过排片id查询,
     * @return
     */
    @RequestMapping("/showschedule1")
    public ModelAndView scheduleMsg1(Integer scheduleId){
        ScheduleMsg scheduleMsg= scheduleService.queryScheduleMsg(scheduleId);
        ModelAndView mav=new ModelAndView();
        mav.addObject("scheduleMsg",scheduleMsg);
        List<CinemaHall> halls=cinemaHallService.selectAllHall();
        mav.addObject("halls",halls);
        mav.setViewName("moviemanager/managerschedule");
        return mav;
    }

    //修改排片信息
    @RequestMapping("/editSchedule")
    @ResponseBody
    public String editSchedule(ScheduleMsg scheduleMsg){
        System.out.println(scheduleMsg);
        if(scheduleService.editSchedule(scheduleMsg)>0){
            return  "success";
        };
      return "fail";
    }


    //修改电影信息
    @RequestMapping("/editMovie")
    @ResponseBody
    public String editMovie(CinemaMovies movies){
        System.out.println(movies);
        if(movieinfoService.editMovie(movies)>0){
            return  "success";
        };
        return "fail";
    }
    /*日期导航条
    * id:主键*/
    @RequestMapping("/findScheduleE")
    @ResponseBody
    public List<ScheduleMsg> scheduleMsgList(Integer id){
        List<ScheduleMsg> scheduleMsgList = scheduleService.queryScheduleMsgList(id);
        return scheduleMsgList;
    }
    /*点击时间辨别并获取数据
    * movieId：电影id
    * begTime:时间 yyy-MM-dd
    * */
    @RequestMapping("/findScheduleET")
    @ResponseBody
    public List<ScheduleMsg> scheduleMsgListTime(Integer movieId,String begTime){
        List<ScheduleMsg>scheduleMsgListTi = scheduleService.queryScheduleMsgTime(movieId,begTime);
        System.out.println(scheduleMsgListTi.toString());
        return scheduleMsgListTi;
    }
    /*页面跳转
    * id：主键*/
    @RequestMapping("/findSchedule")
    public ModelAndView findSchedule(Integer id){
        ScheduleMsg scheduleMsg = scheduleService.queryScheduleMsg(id);
        ModelAndView modelAndView = new ModelAndView();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        modelAndView.addObject("scheduleMsg",scheduleMsg);
        modelAndView.setViewName("movieshow/tickets.html");
        return modelAndView;
    }

    @RequestMapping("/selectByScheduleId")
    @ResponseBody
    public Object selectBySid(Integer id){
        return scheduleService.findById(id);
    }
}
